package org.jeecg.config.init;

import com.alibaba.druid.pool.DruidDataSource;
import org.jeecg.modules.system.entity.SysDataSource;
import org.jeecg.modules.system.service.ISysDataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.List;

@Configuration
public class DynamicBeanDefition {

    static AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext();

    @Autowired
    private static ISysDataSourceService sysDataSourceService;

    static  void createDt(){
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        beanDefinition.setBeanClass(DataSource.class);
        List<SysDataSource> dataSources = sysDataSourceService.list();
        if(dataSources!=null && dataSources.size()>0){
            for (SysDataSource dataSource : dataSources) {
                DruidDataSource druidDataSource=new DruidDataSource();
                druidDataSource.setName(dataSource.getCode());
                druidDataSource.setDriverClassName(dataSource.getDbDriver());
                druidDataSource.setUrl(dataSource.getDbUrl());
                druidDataSource.setUsername(dataSource.getDbUsername());
                druidDataSource.setPassword(dataSource.getDbPassword());
                druidDataSource.setInitialSize(50);
                druidDataSource.setMaxActive(100);
                druidDataSource.setMaxWait(60000);
                druidDataSource.setMinIdle(40);
                druidDataSource.setKeepAlive(true);
                context.registerBean(dataSource.getCode(),DataSource.class,druidDataSource);
            }

            context.refresh();
        }

    }
}
